import React, { Component } from 'react';
import { Animated, ScrollView, View, Image, StatusBar, Text, TouchableOpacity, FlatList, RefreshControl, DeviceEventEmitter, Platform } from 'react-native';
import TabBarTitle from '../components/TabBarTitle';
import Colors from '../constants/Colors';
import StickView from './StickView';
import EmptyView from './EmptyView';
import { width, unitWidth, height } from '../constants/AdapterUtil';
import RefreshFooter from '../components/RefreshFooter';
import { AnimatedButton } from './Button';

export default class StickyListView extends Component {

    //组件属性介绍
    //this.props.headerView   被吸顶布局上面的布局
    //this.props.stickView    被吸顶布局
    //this.props.top          被吸顶布局距离上面多高
    //this.props.scrollStick  被吸顶布局滑动多远后开始被吸顶
    //this.props.stickHeight  被吸顶布局高度
    //this.props.childView    列表子布局 传一个方法然后方法内返回布局
    //this.props.list         列表数据
    //this.props.getList      获取列表数据的方法


    constructor(props) {
        super(props)
        this.state = {
            scrollY: new Animated.Value(0),
            refreshing: false,
            showFoot: 0,//显示上拉加载更多
        }
        this.page = 1;
    }

    componentDidMount() {

    }

    componentWillUnmount() {

    }

    render() {

        let viewList = this._getItemViewList();

        let opacity = this.state.scrollY.interpolate({
            inputRange: [0, 200],
            outputRange: [0, 1] //线性插值，0对应60，0.6对应30，1对应0
        })

        return (
            <View style={{ flex: 1 }}>
                <Animated.ScrollView
                    style={{ flex: 1 }}
                    ref='list'
                    showsVerticalScrollIndicator={false}
                    onScroll={Animated.event(
                        [{
                            nativeEvent: { contentOffset: { y: this.state.scrollY } } // 记录滑动距离
                        }],
                        { useNativeDriver: true }) // 使用原生动画驱动
                    }
                    scrollEnabled={this.props.scrollEnabled}
                    scrollEventThrottle={1}
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.refreshing}
                            onRefresh={this._onRefresh.bind(this)}
                            colors={[Colors.headerColor]}
                            progressBackgroundColor="#ffffff"
                        />
                    }
                    onMomentumScrollEnd={(event) => {
                        const contentHeight = event.nativeEvent.contentSize.height;
                        const scrollViewHeight = event.nativeEvent.layoutMeasurement.height;
                        const scrollOffset = event.nativeEvent.contentOffset.y;

                        const isEndReached = scrollOffset + scrollViewHeight >= contentHeight - (10 * unitWidth); // 是否滑动到底部
                        const isContentFillPage = contentHeight >= scrollViewHeight; // 内容高度是否大于列表高度
                        if (isContentFillPage && isEndReached) {
                            this.onLoadMore();
                        }
                    }} >
                    <View style={{ flex: 1 }}>
                        {this.props.headerView}
                        {this.props.numOfLine && this.props.numOfLine != 1 ?
                            <View style={{
                                marginTop: this.props.stickHeight, minHeight: this.props.minHeight,
                                flexDirection: 'row'
                            }}>
                                {viewList.length > 0 ? this.getNumView(viewList, this.props.numOfLine) : <EmptyView />}
                            </View> :
                            <View style={{
                                marginTop: this.props.stickHeight, minHeight: this.props.minHeight,
                            }}>
                                {viewList.length > 0 ? viewList : <EmptyView />}
                            </View>}
                        <StickView ref='StickView'
                            style={{ position: 'absolute', top: this.props.top }}
                            scrollY={this.state.scrollY}
                            scrollStick={this.props.scrollStick}
                            children={
                                this.props.stickView
                            } />
                        {this.props.list.length > 0 ? <RefreshFooter showFoot={this.state.showFoot} />
                            : null}
                    </View>
                </Animated.ScrollView>
                {this.props.showTopBtn ?
                    <Animated.View style={{ position: 'absolute', right: 20 * unitWidth, bottom: 10 * unitWidth, opacity: opacity }}>
                        <TouchableOpacity onPress={() => {
                            this.scrollTo(0)
                        }} activeOpacity={0.7}>
                            <Image source={require('../res/home_icom_zd.png')} style={{ width: 40 * unitWidth, height: 40 * unitWidth }} resizeMode='stretch' />
                        </TouchableOpacity>
                    </Animated.View> : null}
                {this.props.coverListView}
                {/* //用来覆盖前面的列表 */}
            </View>
        )
    }

    getNumView(list, num) {
        let tempList = {}
        let viewList = []
        for (let i = 0; i < num; i++) {
            tempList[`list${i}`] = []
        }
        for (let i = 0, len = list.length; i < len; i++) {
            let index = i % num;
            tempList[`list${index}`].push(list[i])
        }
        for (let key in tempList) {
            if (tempList.hasOwnProperty(key)) {
                let element = tempList[key];
                viewList.push(<View style={{ width: width / num, overflow: 'hidden' }}>
                    {element}
                </View>)
            }
        }
        return viewList
    }

    scrollTo(y) {
        this.refs.list._component.getScrollResponder().scrollTo({
            x: 0, y: y,
            animated: true,
        })
    }

    _getItemViewList() {
        let viewList = [];
        if (this.props.list) {
            for (let i = 0, len = this.props.list.length; i < len; i++) {
                let item = this.props.list[i];
                // console.log(item)
                viewList.push(this.props.childView ? this.props.childView(item, i) : null);
            }
        }
        return viewList;
    }

    //刷新
    _onRefresh() {
        this.setState({
            refreshing: true,
        });
        this.page = 1;
        this.getList();
    }

    //加载更多
    onLoadMore() {
        // console.log('onLoadMore:' + this.state.showFoot);
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot != 0) {
            return;
        }
        //底部显示正在加载更多数据
        this.page++;
        this.setState({
            showFoot: 2,
        })
        this.getList();
        //获取数据
    }

    getList() {
        this.props.getList ? this.props.getList(this.page) : null;
    }

    //加载更多后有不止10条的数据和刷新时候完成调用
    onHasMore() {
        this.setState({
            refreshing: false,
            showFoot: 0
        })
    }

    //加载更多后没有数据了调用
    onNoMore() {
        this.setState({
            refreshing: false,
            showFoot: 1
        })
    }
}